package com.wl.eb.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wl.eb.mapper.EbProductMapper;
import com.wl.eb.module.EbProduct;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductService {
    //根据ProductId查询该商品的详情
    @Resource
    private EbProductMapper ebProductMapper;
    public EbProduct detail(int productId){
        return ebProductMapper.selectById(productId);
    }

    //根据CategoryId查询该分页数据
    public Page list(int psize,int categoryId){
        Page page = new Page(psize, 6);
        Page productlist = ebProductMapper.selectPage(page, new QueryWrapper<EbProduct>()
                .eq("epc_child_id", categoryId));
        return productlist;
    }

    /**
     * 根据商品id将商品放入购物车(购物车表，session作为购物车)
     * @param id 商品id
     * @return
     */
    public  void addCar(int id, HttpServletRequest request){
        //1.根据id查询商品的所有信息
        EbProduct ebProduct = ebProductMapper.selectById(id);
        //2.购物车中（session）
        HttpSession session = request.getSession();
        //2.1.准备一个蛇皮袋 List
        List<EbProduct> productList= (List<EbProduct>)
                session.getAttribute("car");
        if(productList==null){
            productList= new ArrayList<>();
        }
        //2.2.将商品放入蛇皮袋
            //分商品是否存在购物车、
        boolean flat=false;//假设不存在
        for(int i=0;i<productList.size();i++){
            if(productList.get(i).getEpId().equals(ebProduct.getEpId())){
                productList.get(i).setCount(productList.get(i).getCount()+1);
            flat=true;
            break;
            }
        }
        if(!flat){
            productList.add(ebProduct);
        }

        //2.3将蛇皮袋放入购物车
        session.setAttribute("car",productList);
        System.out.println("放入购物车的商品为："+ebProduct);
    }

    public Map<String, Object> spage(int psize){
        Map<String,Object> result=new HashMap<>();
        //TODO 1.分页查询商品数据 6条
        Page page=new Page(psize,6);
        Page ebProductPage=ebProductMapper.selectPage(page,null);

        result.put("ebProductPage",ebProductPage);

        return result;
    }
}
